<?php

class Commodity_Model extends CI_Model
{
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * @param $row
     * @return Commodity
     */
    public static function getCommodityByRow($row)
    {
        $thatCommodity = new Commodity;
        $thatCommodity->setId($row->id);
        $thatCommodity->setTitle(strip_tags($row->title));
        $thatCommodity->setIntro(strip_tags($row->intro));
        $thatCommodity->setContent($row->content);
        $thatCommodity->setPrice($row->price);
        $thatCommodity->setStock($row->stock);
        $thatCommodity->setContactType($row->contact_type);
        $thatCommodity->setContactInfo($row->contact_info);
        $thatCommodity->setReleaseType($row->release_type);
        $thatCommodity->setReleaseTime($row->release_time);
        $thatCommodity->setImageHash($row->image_hash);
        $thatCommodity->setUserId($row->user_id);
        $thatCommodity->setCommodityCatId($row->commodity_cat_id);
        $thatCommodity->setCommodityTagsIDJson($row->commodity_tags_id_json);
        $thatCommodity->setSchoolunicode($row->schoolunicode);
        return $thatCommodity;
    }

    /**
     * @param Commodity $thatCommodity
     * @return array
     */
    public static function getModelByCommodity($thatCommodity)
    {
        return array(
            'title'                  => strip_tags($thatCommodity->getTitle()),
            'intro'                  => strip_tags($thatCommodity->getIntro()),
            'content'                => $thatCommodity->getContent(),
            'price'                  => $thatCommodity->getPrice(),
            'stock'                  => $thatCommodity->getStock(),
            'contact_type'           => $thatCommodity->getContactType(),
            'contact_info'           => $thatCommodity->getContactInfo(),
            'release_type'           => $thatCommodity->getReleaseType(),
            'release_time'           => $thatCommodity->getReleaseTime(),
            'image_hash'             => $thatCommodity->getImageHash(),
            'user_id'                => $thatCommodity->getUserId(),
            'commodity_cat_id'       => $thatCommodity->getCommodityCatId(),
            'commodity_tags_id_json' => $thatCommodity->getCommodityTagsIDJson(),
            'schoolunicode'          => $thatCommodity->getSchoolunicode(),
        );
    }

    /**
     * @param int $id
     * @return Commodity
     */
    public static function getCommodityById($id)
    {
        /** @var CI $CI */
        $CI =& get_instance();

        $CI->db->select('commodity.*');
        $CI->db->from('commodity');
        $CI->db->where('commodity.id', $id);

        $query = $CI->db->get();
        $row   = $query->row();
        if ($row)
            return self::getCommodityByRow($row);
        else
            return null;
    }


    /**
     * @param string $title
     * @return Commodity
     */
    public static function getCommodityByTitle($title)
    {
        /** @var CI $CI */
        $CI =& get_instance();

        $CI->db->select('commodity.*');
        $CI->db->from('commodity');
        $CI->db->where('commodity.title', $title);

        $query = $CI->db->get();
        $row   = $query->row();
        if ($row)
            return self::getCommodityByRow($row);
        else
            return null;
    }

    /**
     * @param bool|int $limit
     * @param bool|int $offset
     * @param string $orderBy
     * @param string $orderType
     * @return array
     */
    public static function getCommodityArray($limit = false, $offset = false, $orderBy = 'id', $orderType = 'desc')
    {
        /** @var CI $CI */
        $CI =& get_instance();

        $CI->db->select('commodity.*');
        $CI->db->from('commodity');
        $currentSchool = YimeTools::getCurrentSchool();
        if($currentSchool['schoolcode']){
            $CI->db->where('commodity.schoolunicode', $currentSchool['schoolcode']);
        }
        $CI->db->order_by($orderBy, $orderType);

        if ($limit !== false && is_numeric($limit)) {
            if ($offset === false || !is_numeric($offset))
                $offset = 0;
            $CI->db->limit($limit, $offset);
        }

        $query  = $CI->db->get();
        $result = $query->result();

        $array = array();
        foreach ($result as $row) {
            $array[] = self::getCommodityByRow($row);
        }
        return $array;
    }

    /**
     * @param int $commodityCatId
     * @param int|bool $limit
     * @param int|bool $offset
     * @param string $orderBy
     * @param string $orderType
     * @return array
     */
    public static function getCommodityArrayByCommodityCatId($commodityCatId, $limit = false, $offset = false, $orderBy = 'id', $orderType = 'desc')
    {
        /** @var CI $CI */
        $CI =& get_instance();

        $CI->db->select('commodity.*');
        $CI->db->from('commodity');
        $CI->db->where('commodity_cat_id', $commodityCatId);
        $currentSchool = YimeTools::getCurrentSchool();
        if($currentSchool['schoolcode']){
            $CI->db->where('commodity.schoolunicode', $currentSchool['schoolcode']);
        }
        $CI->db->order_by($orderBy, $orderType);

        if ($limit !== false && is_numeric($limit)) {
            if ($offset === false || !is_numeric($offset))
                $offset = 0;
            $CI->db->limit($limit, $offset);
        }

        $query  = $CI->db->get();
        $result = $query->result();

        $array = array();
        foreach ($result as $row) {
            $array[] = self::getCommodityByRow($row);
        }
        return $array;
    }

    /**
     * @param array $commodityCatIdArray
     * @param int|bool $limit
     * @param int|bool $offset
     * @param string $orderBy
     * @param string $orderType
     * @return array
     */
    public static function getDescendantCommodityArrayByCommodityCatIdArray($commodityCatIdArray, $limit = false, $offset = false, $orderBy = 'id', $orderType = 'desc')
    {
        /** @var CI $CI */
        $CI =& get_instance();

        $CI->db->select('commodity.*');
        $CI->db->from('commodity');
        foreach ($commodityCatIdArray as $thisCatId) {
            $CI->db->or_where('commodity.commodity_cat_id', $thisCatId);
        }
        $CI->db->order_by($orderBy, $orderType);

        if ($limit !== false && is_numeric($limit)) {
            if ($offset === false || !is_numeric($offset))
                $offset = 0;
            $CI->db->limit($limit, $offset);
        }

        $query  = $CI->db->get();
        $result = $query->result();

        $array = array();
        foreach ($result as $row) {
            $array[] = self::getCommodityByRow($row);
        }
        return $array;
    }

    /**
     * @param int $userId
     * @param int|bool $limit
     * @param int|bool $offset
     * @param string $orderBy
     * @param string $orderType
     * @return array
     */
    public static function getCommodityArrayByUserId($userId, $limit = false, $offset = false, $orderBy = 'id', $orderType = 'desc')
    {
        /** @var CI $CI */
        $CI =& get_instance();

        $CI->db->select('commodity.*');
        $CI->db->from('commodity');
        $CI->db->where('commodity.user_id', $userId);
        $CI->db->order_by($orderBy, $orderType);

        if ($limit !== false && is_numeric($limit)) {
            if ($offset === false || !is_numeric($offset))
                $offset = 0;
            $CI->db->limit($limit, $offset);
        }

        $query  = $CI->db->get();
        $result = $query->result();

        $array = array();
        foreach ($result as $row) {
            $array[] = self::getCommodityByRow($row);
        }
        return $array;
    }

    /**
     * @param $searchStr
     * @param int|bool $limit
     * @param int|bool $offset
     * @param string $orderBy
     * @param string $orderType
     * @return array
     */
    public static function getCommodityArrayBySearchString($searchStr, $limit = false, $offset = false, $orderBy = 'id', $orderType = 'desc')
    {
        /** @var CI $CI */
        $CI =& get_instance();

        $CI->db->select('commodity.*');
        $CI->db->from('commodity');
        $CI->db->like('commodity.title', $searchStr);
        $CI->db->or_like('commodity.intro', $searchStr);
        $CI->db->or_like('commodity.content', $searchStr);
        $CI->db->order_by($orderBy, $orderType);

        $currentSchool = YimeTools::getCurrentSchool();
        if($currentSchool['schoolcode']){
            $CI->db->where('commodity.schoolunicode', $currentSchool['schoolcode']);
        }

        if ($limit !== false && is_numeric($limit)) {
            if ($offset === false || !is_numeric($offset))
                $offset = 0;
            $CI->db->limit($limit, $offset);
        }

        $query  = $CI->db->get();
        $result = $query->result();

        $array = array();
        foreach ($result as $row) {
            $array[] = self::getCommodityByRow($row);
        }
        return $array;
    }

    /**
     * @param int $releaseType
     * @param int|bool $limit
     * @param int|bool $offset
     * @return array
     */
    public static function getCommodityArrayByReleaseType($releaseType, $limit = false, $offset = false)
    {
        /** @var CI $CI */
        $CI =& get_instance();

        $CI->db->select('commodity.*');
        $CI->db->from('commodity');
        $CI->db->where('release_type', $releaseType);
        $currentSchool = YimeTools::getCurrentSchool();
        if ($currentSchool['schoolcode']) {
            $CI->db->where('commodity.schoolunicode',$currentSchool['schoolcode']);
        }
        $CI->db->order_by('id', 'desc');

        if ($limit !== false && is_numeric($limit)) {
            if ($offset === false || !is_numeric($offset))
                $offset = 0;
            $CI->db->limit($limit, $offset);
        }

        $query  = $CI->db->get();
        $result = $query->result();

        $array = array();
        foreach ($result as $row) {
            $array[] = self::getCommodityByRow($row);
        }
        return $array;
    }

    /**
     * @return int
     */
    public static function countCommodity()
    {
        /** @var CI $CI */
        $CI =& get_instance();

        $CI->db->select('commodity.id');
        $CI->db->from('commodity');
        $currentSchool = YimeTools::getCurrentSchool();
        if($currentSchool['schoolcode']){
            $CI->db->where('commodity.schoolunicode', $currentSchool['schoolcode']);
        }

        return $CI->db->count_all_results();
    }

    /**
     * @param $userId
     * @return int
     */
    public static function countCommodityByUserId($userId)
    {
        /** @var CI $CI */
        $CI =& get_instance();

        $CI->db->select('commodity.*');
        $CI->db->from('commodity');
        $CI->db->where('commodity.user_id', $userId);
        $currentSchool = YimeTools::getCurrentSchool();
        if($currentSchool['schoolcode']){
            $CI->db->where('commodity.schoolunicode', $currentSchool['schoolcode']);
        }

        return $CI->db->count_all_results();
    }

    /**
     * @param $releaseType
     * @return int
     */
    public static function countCommodityByreleaseType($releaseType)
    {
        /** @var CI $CI */
        $CI =& get_instance();

        $CI->db->select('commodity.*');
        $CI->db->from('commodity');
        $CI->db->where('commodity.release_type', $releaseType);
        $currentSchool = YimeTools::getCurrentSchool();
        if($currentSchool['schoolcode']){
            $CI->db->where('commodity.schoolunicode', $currentSchool['schoolcode']);
        }

        return $CI->db->count_all_results();
    }

    /**
     * @param string $searchStr
     * @return int
     */
    public static function countCommodityBySearchString($searchStr)
    {
        /** @var CI $CI */
        $CI =& get_instance();

        $CI->db->select('commodity.*');
        $CI->db->from('commodity');
        $CI->db->like('commodity.title', $searchStr);
        $CI->db->or_like('commodity.intro', $searchStr);
        $CI->db->or_like('commodity.content', $searchStr);

        $currentSchool = YimeTools::getCurrentSchool();
        if($currentSchool['schoolcode']){
            $CI->db->where('commodity.schoolunicode', $currentSchool['schoolcode']);
        }

        return $CI->db->count_all_results();
    }

    /**
     * @param array $catIdArray
     * @return int
     */
    public static function countCommodityByCommodityCategoryIdArray($catIdArray)
    {
        if (sizeof($catIdArray) == 0) return 0;

        /** @var CI $CI */
        $CI =& get_instance();

        $CI->db->select('commodity.id');
        $CI->db->from('commodity');
        $currentSchool = YimeTools::getCurrentSchool();
        if($currentSchool['schoolcode']){
            $CI->db->where('commodity.schoolunicode', $currentSchool['schoolcode']);
        }
        /*
        foreach ($catIdArray as $thisCatId) {
            $CI->db->or_where('commodity.commodity_cat_id', $thisCatId);
        }
        */
        $CI->db->where_in('commodity.commodity_cat_id', $catIdArray);

        return $CI->db->count_all_results();
    }

    /**
     * @param Commodity $thatCommodity
     * @throws DatabaseException
     * @return Commodity
     */
    public static function add($thatCommodity)
    {
        /** @var CI $CI */
        $CI =& get_instance();

        $result = $CI->db->insert('commodity', self::getModelByCommodity($thatCommodity));
        if ($result)
            return self::getCommodityById($CI->db->insert_id());
        else
            throw new DatabaseException('插入数据失败');
    }

    /**
     * @param Commodity $thatCommodity
     * @throws DatabaseException
     * @return Commodity
     */
    public static function update($thatCommodity)
    {
        /** @var CI $CI */
        $CI =& get_instance();

        $CI->db->where('id', $thatCommodity->getID());
        $result = $CI->db->update('commodity', self::getModelByCommodity($thatCommodity));
        if ($result)
            return self::getCommodityById($thatCommodity->getID());
        else
            throw new DatabaseException('更新数据失败');
    }

    /**
     * @param Commodity $thatCommodity
     * @throws DatabaseException
     * @return bool
     */
    public static function delete($thatCommodity)
    {
        /** @var CI $CI */
        $CI =& get_instance();

        $CI->db->where('id', $thatCommodity->getID());
        $result = $CI->db->delete('commodity');
        if ($result)
            return true;
        else
            throw new DatabaseException('删除数据失败');
    }

    public static function countCommodityFavoriteByCommodityId($commodityId)
    {
        CommodityFavorite_Model::countCommodityFavoriteByCommodityId($commodityId);
    }

}
